package h0812;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 根据ip查找城市
 * @date 2024/8/12 17:22
 */
public class FindCitiesByIp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] cities = sc.nextLine().split(";");
        //?:匹配多项
        Pattern p = Pattern.compile("(\\w+)=((?:\\d{1,3}\\.){3}\\d{1,3}),((?:\\d{1,3}\\.){3}\\d{1,3})");
        HashMap<String, List<String[]>> map = new HashMap<>();
        for (int i = 0; i < cities.length; i++) {
            Matcher matcher = p.matcher(cities[i]);
            if (matcher.find()){
                String group = matcher.group(1);
                List<String[]> list = map.get(group);

                if (list!=null) {
                    list.add(new String[]{matcher.group(2), matcher.group(3)});
                } else {
                    list = new ArrayList<>();
                    list.add(new String[]{matcher.group(2), matcher.group(3)});
                    map.put(group, list);
                }
            }
        }
        //判断是否在范围内
        String[] ipAddresses = sc.nextLine().split(",");
        sc.close();
        StringJoiner joiner = new StringJoiner(",");

        for (String ip : ipAddresses) {
            String closedCity="";
            long smallestRange = Long.MAX_VALUE;
            long ipVal=toLong(ip);
            for (String city : map.keySet()) {
                for (String[] s : map.get(city)) {
                    long left = toLong(s[0]);
                    long right=toLong(s[1]);
                    long range = right - left;
                    if (ipVal>=left&&ipVal<=right){
                        //找到了，把城市名假如到结果中。
                        if (range<smallestRange){
                            //更新最优范围
                            smallestRange=range;
                            closedCity=city;
                        }
                    }
                }
            }
            //TODO 这里的String closedCity=""; 直接包含两种找到找不到两种情况。
            joiner.add(closedCity);

        }
        System.out.println(joiner);

    }

    //TODO ip字符串转整数
    private static long toLong(String s) {
        String[] ipParts=s.split("\\.");
        long result=0;
        for (int i = 0; i < 4; i++) {
            result<<=8;
            result|=Integer.parseInt(ipParts[i]);
        }
        return result;
    }
    //TODO 整数转ip
    private static String toIp(long num){
        StringBuilder res = new StringBuilder();
        //24 16 8 0
        for (int i = 3; i >=0 ; i--) {
            long temp=num>>i*8;
            long l = temp& 0xFF;
            res.append(l);
            if (i>0){
                res.append(".");
            }
        }
        return res.toString();
    }
}
